package com.axones.planningpoker.rest.service;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.restlet.data.Status;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

import com.axones.planningpoker.bean.User;
import com.axones.planningpoker.dao.UserDAO;
import com.google.gson.Gson;

public class PasswordResource extends ServerResource {
	private static UserDAO userDao;
	private static Gson gson;

	public PasswordResource() {
		if (userDao == null) {
			userDao = new UserDAO();
		}
		if (gson == null) {
			gson = new Gson();
		}
	}

	@Get
	public void doGet() {
		String email = (String) getRequest().getAttributes().get("email");

		User user = userDao.find(email);

		if (user != null) {
			sendMail("planningpoker@axones.com",user.getEmail(),"Axones Planning Poker - Password recovery","Your password is : " + user.getPassword());
			setStatus(Status.SUCCESS_OK);
		} else {
			setStatus(Status.CLIENT_ERROR_NOT_FOUND);
		}
	}
	
	private void sendMail(String from, String to, String subject, String message) {
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);

		try {
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(from));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
			msg.setSubject(subject);
			msg.setText(message);
			Transport.send(msg);

		} catch (AddressException e) {
			// ...
		} catch (MessagingException e) {
			// ...
		}
	}
}
